import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { IStrategyOptions, Strategy } from 'passport-local';
import { Repository } from 'typeorm';
import Admin from 'src/entities/admin/admin.entity';
import { BadRequestException } from '@nestjs/common';
import { compareSync } from 'bcryptjs';

/**
 * 后台管理登录策略
 */
export class AuthStorage extends PassportStrategy(Strategy) {
  constructor(
    @InjectRepository(Admin)
    private readonly adminRepository: Repository<Admin>,
  ) {
    super({
      usernameField: 'username', // 验证用户名的字段
      passwordField: 'password', // 验证密码的字段
    } as IStrategyOptions);
  }

  async validate(username: string, password: string) {
    const admin = await this.adminRepository
      .createQueryBuilder('admin')
      .addSelect('admin.password') // 因为密码字段做了序列化, 所以需要显示的查询
      .where('admin.username=:username', { username })
      .getOne();

    if (!admin) {
      throw new BadRequestException('用户名或密码错误');
    }
    if (!compareSync(password, admin.password)) {
      throw new BadRequestException('用户名或密码错误');
    }
    return admin;
  }
}
